// Copyright (c) 2011 The Kiwii Authors. All rights reserved.
// Use of this source code is governed by the New BSD License that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#ifndef KIWII_EVENT_INCLUDED
#define KIWII_EVENT_INCLUDED

#include "EventLoopBase.hxx"

namespace kiwii {
  namespace net {

    struct IOEvent {
      IOEvent() : events_(EV_NONE), readHandler_(0), writeHandler_(0) {}

      unsigned int events_;
      IOEventHandler readHandler_;
      IOEventHandler writeHandler_;
    };

    struct FiredIOEvent {
      FiredIOEvent(int fd, unsigned int events) : fd_(fd), events_(events) {}

      int fd_;
      unsigned int events_;
    };

    struct TimeEvent {
      TimeEvent(long long milliseconds, TimeEventHandler const& handler);
      struct timeval timeout() const;
      bool isExpired() const;
      void setExpireTime(long long milliseconds);

      int id_;
      long whenSeconds_;
      long whenMilliseconds_;
      TimeEventHandler handler_;

      static int nextTimerId_;
    };

    //Since we want to use the TimeEvent in the standard priority queue that
    //is based on the heap algorithm, we have to overload the operator< for
    //the TimeEvent class that will be used by the priority queue to sort the
    //elements in the queue.
    //For TimeEvent, whichever has the shortest time has the highest priority.
    inline bool operator<(TimeEvent const& te1, TimeEvent const& te2) {
      if (te1.whenSeconds_ < te2.whenSeconds_) {
	return false;
      } else if (te1.whenSeconds_ == te2.whenSeconds_) {
	if (te1.whenMilliseconds_ < te2.whenMilliseconds_) return false;
	else return true;
      } else {
	return true;
      }
    }

  }
}

#endif
